﻿namespace EFS.RC.CCAdmin.Supervisors
{
	public partial class Edit : EFS.RC.CCAdmin.Common.Control
	{
		private System.Int32 officeEndpointID = 0;
		private EFS.RC.CC.Deployment.Views.Operators.SupervisorADDetails supervisorDetails;
		private EFS.Common.UI.Controls.ModalDialogHost host = null;

		#region Constructors

		public Edit()
		{
			InitializeComponent();

			// ignore in desiger
			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
			{
				throw new System.Exception("Do not use this constructor at runtime!");
			}
		}

		public Edit(
			EFS.Common.UI.Controls.ModalDialogHost host,
			EFS.RC.CC.Deployment.Views.Operators.SupervisorADDetails supervisorDetails,
			System.Int32 officeEndpointID)
		{
			InitializeComponent();

			//set
			this.host = host;
			this.officeEndpointID = officeEndpointID;
			this.supervisorDetails = supervisorDetails;

			// set events
			this.Loaded += new System.Windows.RoutedEventHandler(Edit_Loaded);

			// service events
			UtilitiesService.Supervisor_CreateCompleted += new System.EventHandler<WebProxy.Supervisor_CreateCompletedEventArgs>(UtilitiesService_Supervisor_CreateCompleted);
		}

		#endregion

		#region Search AD

		/// Called when search is close
		private void OnSearchWIndowClosed(EFS.Common.UI.Controls.ModalDialogHost host)
		{
			// search
			EFS.RC.CCAdmin.AD.Search opSearch = (EFS.RC.CCAdmin.AD.Search)host.HostedContent;

			// Ok clicked
			if (host.DialogClosedReason == EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok)
			{
				// logon name
				EFS.AD.User user = opSearch.SelectedUser;

				// create
				UtilitiesService.Supervisor_CreateAsync(officeEndpointID, user.ObjectGuid.ToString());
			}
			else
			{
				this.host.Close();
			}
		}
		#endregion

		#region Service events

		/// UtilitiesService_Supervisor_CreateCompleted
		private void UtilitiesService_Supervisor_CreateCompleted(object sender, WebProxy.Supervisor_CreateCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Unable to Add Supervisor. ", e.Error);
			}
			else
			{
				host.Close(EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok);
			}
		}

		#endregion

		#region Events
		/// Load
		private void Edit_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			// CREATE
			if (null == supervisorDetails)
			{
				EFS.Common.UI.Controls.ModalDialogHost wnd = new EFS.Common.UI.Controls.ModalDialogHost();
				wnd.HostedContent = new EFS.RC.CCAdmin.AD.Search();
				wnd.Show(OnSearchWIndowClosed);
			}
			else
			{
				// set data
				textBoxLogonName.Text = supervisorDetails.DomainLogonName;
				textBoxFirstName.Text = supervisorDetails.FirstName;
				textBoxLastName.Text = supervisorDetails.LastName;
			}
		}

		#endregion
	}

}